'''
Author: your name
Date: 2021-11-05 14:51:59
LastEditTime: 2021-11-12 11:12:18
LastEditors: Please set LastEditors
Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
FilePath: /tinyms/tinyms-api/apps/cms/site/views.py
'''
from crypt import methods
from flask import request
from  . import cms_site
from .model import Site
from .service import SiteService
from apps.utils import auty
from apps.utils.TypeUtils import TypeUtils

import json
import time

@cms_site.route('/saveOrUpdate',methods=['GET','POST'])
def save():
    data = {}
    if request.method == "POST":
        for key in request.form:
            data[key] = request.form.get(key)
    else:
        for key in request.args:
            data[key] = request.args.get(key)
    site = Site()
    site.site_name =  data['site_name']
    site.site_domain = data['site_domain']
    site.site_path = data['site_path']
    site.site_template = data['site_template']
    site.site_time = data['site_time']
    site.site_remarks = data['site_remarks']
    site.site_state = data['site_state']

    if not data['site_pk']:
        SiteService.save(site)
    else:
        site.site_pk = data['site_pk']
        site.site_name =  data['site_name']
        site.site_domain = data['site_domain']
        site.site_path = data['site_path']
        site.site_template = data['site_template']
        site.site_time = data['site_time']
        site.site_remarks = data['site_remarks']
        site.site_state = data['site_state']
        SiteService.update(site)
    
    data = {
        'msg':'保存成功',
        'code':'0'
    }
    return json.dumps(data,ensure_ascii=False)

@cms_site.route('/pages',methods = ['GET','POST'])
@auty.login_required
def pages():
    if request.method == "POST":
        page = request.form.get("page") #获取页码
    else:
        page = request.args.get("page")
    pages = SiteService.pages(page)    
    #将分页对象组装为需要的数据
    data = {
        'msg':'success',
        'code':0,
        'data':[TypeUtils.list_to_dict(site) for site in pages.items],
        'count':pages.total
    }
    print(pages.items)
    return json.dumps(data,ensure_ascii=False)

''''
通过主键删除数据
'''
@cms_site.route("/delete",methods={"POST","GET"})
@auty.login_required
def delete():
    if request.method == "POST":
        site_pk = request.form.get("site_pk") #获取页码
    else:
        site_pk = request.args.get("site_pk")    
    SiteService.delete(site_pk)
    data = {
        'msg':'删除成功',
        'code':'0'
    }
    return json.dumps(data,ensure_ascii=False)